<script setup>
import { ref, reactive, onMounted, toRaw, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {Edit, Delete, Search} from '@element-plus/icons-vue'

//引入API
// import {} from '../../api/dept.js'

const tableLoading = ref(true);
// 数据
const currentPageNum = ref(1);//当前页码
const currentPageSize = ref(5);//每页显示的最大数据量
const dataArr = ref([]);//当前页数据
const total = ref(0);//总数据量

function doLoadTableDatas() {//加载表格数据
    tableLoading.value = true;//开始加载
    //TODO: 使用API(提供了数据服务才能使用,否则会出错)根据条件加载数据
    //主要查询条件 currentPageNum,currentPageSize,searchFormData
    let params = {
        pageNum: currentPageNum.value,
        pageSize: currentPageSize.value,
        name: searchFormData.value.name,
        addr: searchFormData.value.addr,
    };
    console.log('search params:', params);

    //模拟数据加载操作
    const loadData = () => {
        return {
            total: 100,
            data: [
                {id:1,name:'tom1',addr:'南京xxx1'},
                {id:2,name:'tom2',addr:'南京xxx2'},
                {id:3,name:'tom3',addr:'南京xxx3'},
                {id:4,name:'tom4',addr:'南京xxx4'},
                {id:5,name:'tom5',addr:'南京xxx5'},
            ]
        }
    };
    const result = loadData();

    //成功后执行以下操作
    //处理响应数据
    dataArr.value = result.data;
    total.value = result.total;
    tableLoading.value = false;//加载完成
    
}

onMounted(()=> {//挂载后执行
    doLoadTableDatas();//核心表格数据
});

const tableSelectObj = ref(null);//选中行对象
function doTableSelectionChange(selected) {//选中操作
    //选中变化
    console.log('doTableSelectionChange:', selected);
    tableSelectObj.value = selected;
}

//一次只能操作一个数据
function doModify() {//修改对话框
    if(tableSelectObj.value == null) {
        ElMessage.warning('请选择需要修改的行');
        return;
    }
    //设置数据
    const obj = toRaw(tableSelectObj.value);//取原对象
    const newValue = structuredClone(obj);//克隆
    formData.value = newValue;

    //成功后打开对话框
    dialogFlag.value = true;
}
function doRemove() {//删除
    if(tableSelectObj.value == null) {
        ElMessage.warning('请选择需要删除的行');
        return;
    }
    //TODO: 执行数据删除

    //成功后执行以下操作
    ElMessage.success('删除成功');
    //重新加载数据
    doLoadTableDatas();
}

function createFormData() {//表单数据对象模板
    return {id:undefined,name:'',addr:''};
}
//对话框中表单数据
const formData = ref(createFormData());
const dialogFlag = ref(false);//控制对话框
function doDialogBeforeClose(done) {
    //关闭操作
    done();
    formRef.value.clearValidate();//清除校验标记
}
function doCloseDialog(type) {
    if(type === 0) {
        //取消操作
        dialogFlag.value = false;
        formRef.value.clearValidate();//清除校验标记
        return;
    }
    if(type === 1) {
        //确定操作
        doFormSubmit();
    }
}
const formRef = ref(null);//表单组件
const formRules = reactive({//校验规则
    name: [{required:true, validator: (rule, value, callback)=>{
        if(!value) {
            callback(new Error('请填写部门名称'));
            return;
        }
        if(value.length > 20) {
            callback(new Error('部门名称长度范围是1~20'));
            return;
        }
        //TODO: 发送请求,校验是否重复
        setTimeout(()=>{//模拟
            if(Math.random() > 0.7) {
                callback();//成功
            } else {
                callback(new Error('该部门名称已存在'));//失败
            }
        }, 500);
    }, trigger:'blur'}],
    addr: [
        {required:true, message:'请填写所在位置', trigger:'blur'},
        {min:1, max:10, message:'内容长度是1~100', trigger:'blur'},
    ]
});
function doFormSubmit() {//表单校验与提交
    formRef.value.validate((valid, fields) => {
        if (valid) {
            console.log('校验通过');
            //TODO: 提交修改信息
            let params = toRaw(formData.value);
            console.log('submit:', params);

            //成功后执行以下操作
            dialogFlag.value = false;//成功,关闭对话框
            ElMessage.success('修改成功');
            //重新加载数据
            doLoadTableDatas();
        } else { 
            //console.log('校验不通过:', fields);
            ElMessage.warning('信息有误，请查看对应的提示信息');
        }
    });;
}

//搜索
const searchFormData = ref({name:'',addr:''});
const searchFormRef = ref(null);
function doFormSearch() {
    if(tableLoading.value) {
        ElMessage.warning('正在查询中...');
        return;
    }
    //console.log('searchFormData:', toRaw(searchFormData.value));
    let oldPageNum = currentPageNum.value;
    currentPageNum.value = 1;//从头开始查询
    if(oldPageNum == 1) {//防止重复加载
        // 根据条件加载数据
        doLoadTableDatas();
    }
}

//分页变化,加载数据
watch(currentPageNum, (nv, ov, onCleanup)=>{
    doLoadTableDatas();
});
watch(currentPageSize, (nv, ov, onCleanup)=>{
    doLoadTableDatas();
});

</script>
<template>
    <div>
        <div class="title-dl">部门信息列表</div>
        <div class="tool-btns" >
            <!-- search表单 -->
            <el-form :model="searchFormData" :inline="true" ref="searchFormRef" >
                <el-form-item label="部门名称：" prop="name">
                    <el-input v-model="searchFormData.name" autocomplete="off" placeholder="请输入" clearable style="width: 160px" />
                </el-form-item>
                <el-form-item label="部门位置：" prop="addr">
                    <el-input v-model="searchFormData.addr" autocomplete="off" placeholder="请输入" clearable style="width: 160px" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="doFormSearch">查询</el-button>
                </el-form-item>
            </el-form>
            <el-button type="primary" :icon="Edit" @click="doModify">修改</el-button>
            <el-button type="danger" :icon="Delete" @click="doRemove">删除</el-button>
        </div>
        <div class="content-dl" v-loading="tableLoading" >
            <!-- 根据情况增减列 -->
            <el-table :data="dataArr" stripe border @current-change="doTableSelectionChange" highlight-current-row>
                <el-table-column prop="id" label="编号" width="120" />
                <el-table-column prop="name" label="部门名称" width="240" show-overflow-tooltip />
                <el-table-column prop="addr" label="部门位置" show-overflow-tooltip />
            </el-table>
            <el-pagination class="page-dl" layout="total, jumper, prev, pager, next" :total="total"
            v-model:current-page="currentPageNum" v-model:page-size="currentPageSize"
            :pager-count="5" hide-on-single-page size="large" />
        </div>

        <!-- 修改对话框 destroy-on-close关闭时销毁 -->
        <el-dialog v-model="dialogFlag" title="部门编辑" width="500" 
        :before-close="doDialogBeforeClose" center align-center draggable
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        >
            <el-form :model="formData" label-width="130px" :rules="formRules" 
            status-icon ref="formRef">
                <el-form-item label="部门名称：" prop="name">
                    <el-input v-model="formData.name" autocomplete="off" />
                </el-form-item>
                <el-form-item label="部门位置：" prop="addr">
                    <el-input type="textarea" v-model="formData.addr" autocomplete="off" autosize />
                </el-form-item>
            </el-form>
            <template #footer>
                <div>
                    <el-button @click="doCloseDialog(0)">取消</el-button>
                    <el-button type="primary" @click="doCloseDialog(1)">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<style scoped>
.title-dl {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 10px;
}
.tool-btns {
    margin-bottom: 10px;
}
.page-dl {
    margin-top: 10px;
}
</style>